<template>
  <Dialog
    v-model="show"
    :title="props.data?.id ? $t('discountActivity.编辑折扣活动') : $t('discountActivity.新增折扣活动')"
    width="600px"
    @close="close"
    @confirm="handleSubmit"
  >
    <div class="h-600 overflow-y-auto">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item :label="$t('discountActivity.活动名称')" prop="name">
          <el-input v-model="formData.name" :placeholder="$t('discountActivity.请输入活动名称')" />
        </el-form-item>

        <el-form-item :label="$t('discountActivity.选择店铺')" prop="tenantId">
          <el-select
            v-model="formData.tenantId"
            filterable
            :placeholder="$t('discountActivity.请选择店铺')"
            @change="handleShopChange"
          >
            <el-option
              v-for="item in shopOptions"
              :key="item.id"
              :label="item['name' + locale]"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item :label="$t('discountActivity.选择商品')" prop="products">
          <div class="d-flex align-items-center">
            <el-button
              type="primary"
              @click="openProductDialog"
              :disabled="!formData.tenantId"
              >{{ $t('discountActivity.选择商品') }}</el-button
            >
            <span v-if="formData.products.length" class="ml-2">
              {{ $t('discountActivity.已选商品') }}：{{ formData.products.length }}件
            </span>
            <span v-if="!formData.tenantId" class="ml-2 color-999999">
              {{ $t('discountActivity.请先选择店铺') }}
            </span>
          </div>
        </el-form-item>

        <el-table
          class="mb12"
          :data="formData.products"
          row-key="id"
          height="320"
          v-if="formData.products.length"
        >
          <el-table-column :label="$t('discountActivity.商品图片')" width="100">
            <template #default="{ row }">
              <el-image :src="row.image" style="width: 50px; height: 50px" />
            </template>
          </el-table-column>
          <el-table-column :label="$t('discountActivity.商品名称')" :prop="'name' + locale" />
          <el-table-column :label="$t('discountActivity.商品价格')" prop="minPrice" />
          <el-table-column :label="$t('discountActivity.店铺名称')" :prop="'tenantName' + locale" />
          <el-table-column :label="$t('discountActivity.操作')" width="100" fixed="right">
            <template #default="{ row }">
              <el-button type="text" @click="handleDelete(row)">{{ $t('discountActivity.删除') }}</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-form-item :label="$t('discountActivity.折扣')" prop="discountRate">
          <el-input-number
            v-model="formData.discountRate"
            :min="0"
            :max="100"
            :precision="0"
            :step="1"
          />
        </el-form-item>

        <el-form-item :label="$t('discountActivity.活动时间')" prop="activityTime">
          <el-date-picker
            v-model="formData.activityTime"
            type="datetimerange"
            :range-separator="$t('datePick.至')"
            :start-placeholder="$t('discountActivity.开始日期')"
            :end-placeholder="$t('discountActivity.结束日期')"
          />
        </el-form-item>
      </el-form>
    </div>
  </Dialog>

  <!-- 选择商品弹窗 -->
  <Dialog
    v-model="productDialogVisible"
    :title="$t('discountActivity.选择商品')"
    width="800px"
    @confirm="confirmProducts"
  >
    <div class="mb-3 flex_aic_jcsb">
      <el-input
        v-model="productSearchKey"
        :placeholder="$t('discountActivity.请输入商品名称')"
        style="width: 300px"
        clearable
      />
      <el-button type="primary" @click="handleProductSearch">{{ $t('discountActivity.搜索') }}</el-button>
    </div>

    <el-table
      :data="productList"
      @selection-change="handleSelectionChange"
      row-key="id"
      ref="multipleTableRef"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" :label="$t('discountActivity.序号')" width="60" />
      <el-table-column :label="$t('discountActivity.商品图片')" width="100">
        <template #default="{ row }">
          <el-image :src="row.image" style="width: 50px; height: 50px" />
        </template>
      </el-table-column>
      <el-table-column :prop="'name' + locale" :label="$t('discountActivity.商品名称')" />
      <el-table-column prop="minPrice" :label="$t('discountActivity.商品价格')" />
      <el-table-column :prop="'tenantName' + locale" :label="$t('discountActivity.店铺名称')" />
    </el-table>
  </Dialog>
</template>

<script setup>
import { ref, computed, watch, onMounted, nextTick } from "vue";
import Dialog from "@/components/dialog.vue";
import Api from "@/config/api/api";
import moment from "moment";
import { ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";

const { locale, t } = useI18n();

const multipleTableRef = ref();
const show = defineModel();
const emit = defineEmits(["success"]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(100);
const props = defineProps({
  data: {
    type: Object,
    default: () => ({}),
  },
});

// 表单数据
const formData = ref({
  name: "",
  tenantId: "",
  products: [],
  discountRate: "",
  activityTime: [],
});

// 表单校验规则
const rules = {
  name: [{ required: true, message: t('discountActivity.请输入活动名称'), trigger: "blur" }],
  tenantId: [{ required: true, message: t('discountActivity.请选择店铺'), trigger: "change" }],
  products: [{ required: true, message: t('discountActivity.请选择商品'), trigger: "change" }],
  discountRate: [{ required: true, message: t('discountActivity.请输入折扣'), trigger: "change" }],
  activityTime: [
    { required: true, message: t('discountActivity.请选择活动时间'), trigger: "change" },
  ],
};

// 店铺选项
const shopOptions = ref([]);
// 商品弹窗相关
const productDialogVisible = ref(false);
const productSearchKey = ref("");
const productList = ref([]);
const selectedProducts = ref([]);

const getDetail = () => {
  Api.skuActivity_detail(props.data.id).then((res) => {
    if (res.status === 200) {
      // detailInfo.value = res.data;
      formData.value = {
        ...res.data,
        products: res.data.skus,
        activityTime: [moment(res.data.startTime), moment(res.data.endTime)],
      };
    }
  });
};

watch(show, (val) => {
  if (val && props.data?.id) {
    getDetail();
    // 编辑模式，加载数据
    // formData.value = {
    //   ...props.data,
    //   products: [],
    //   activityTime: [moment(props.data.startTime), moment(props.data.endTime)],
    // };
  }
});

const formRef = ref();

// 打开商品选择弹窗
const openProductDialog = async () => {
  currentPage.value = 1;
  productDialogVisible.value = true;
  getProductList();
};

// 处理商品搜索
const handleProductSearch = () => {
  currentPage.value = 1;
  getProductList();
};

// 处理商品选择
const handleSelectionChange = (selection) => {
  selectedProducts.value = selection;
};

// 确认选择商品
const confirmProducts = () => {
  formData.value.products = selectedProducts.value;
  productDialogVisible.value = false;
};

const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      const submitData = {
        name: formData.value.name,
        tenantId: formData.value.tenantId,
        skus: selectedProducts.value.map((v) => ({ id: v.id })),
        discountRate: formData.value.discountRate,
        startTime: moment(formData.value.activityTime[0]).valueOf(),
        endTime: moment(formData.value.activityTime[1]).valueOf(),
      };
      Api.skuActivity_add(submitData).then((res) => {
        if (res.status === 200) {
          ElMessage.success(t('discountActivity.操作成功'));
          emit("success", submitData);
          close();
        }
      });
    }
  });
};

const close = () => {
  formData.value = {
    name: "",
    tenantId: "",
    products: [],
    discountRate: "",
    activityTime: [],
  };
  show.value = false;
  formRef.value.resetFields();
};

// 获取店铺列表
const getSellerList = () => {
  Api.getTenantList({
    page: 0,
    size: 9999,
    status: 2,
  }).then((res) => {
    shopOptions.value = res.data.content || [];
  });
};

// 获取商品列表
const getProductList = async () => {
  await Api.sku_list({
    page: currentPage.value - 1,
    size: pageSize.value,
    ['name' + locale.value]: productSearchKey.value,
    tenantId: formData.value.tenantId,
    status: 1,
  }).then((res) => {
    productList.value = res.data.content || [];
    total.value = +res.data.totalElements || 0;
    nextTick(() => {
      const rows = productList.value?.filter((v) =>
        formData.value.products.find((v2) => v2.id === v.id)
      );
      rows.forEach((row) => {
        multipleTableRef.value?.toggleRowSelection(row);
      });
    });
  });
};

// 删除商品
const handleDelete = (row) => {
  formData.value.products = formData.value.products.filter(
    (v) => v.id !== row.id
  );
};

onMounted(() => {
  getSellerList();
});
</script>

<style lang="scss" scoped>
.h-600 {
  height: 600px;
}
.lht-38 {
  line-height: 38px;
}
.w-120 {
  width: 120px;
}
.mt24 {
  margin-top: 24px;
}
</style>
